package com.dotstone.chipism.activity;

import org.json.JSONArray;
import org.json.JSONObject;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.bean.MySocket.RecDataCallBackListener_Serach;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.listener.OnDeviceStatusListener;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class RemoteSwitchActivity extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private Button mPowerB;
	private TextView mTitleTv;
	private boolean power = false;
	private String address;
	private MySocket socket;
	private String id;
	private Device device;
	private SVProgressHUD mSVProgressHUD;
	private boolean needToCheck = true;
	private int times = 0;
	private View bg;
	private boolean received = false;
	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.power_b:
			if (power) { // 当前打开 发送关指令
				mPowerB.setBackgroundResource(R.drawable.kaiguan22x);
				bg.setBackgroundResource(R.drawable.btn065);
				sendCmd(device.getCloseCmd());
			} else { // 当前关闭 发送开的指令
				mPowerB.setBackgroundResource(R.drawable.kaiguan12x);
				bg.setBackgroundResource(R.drawable.bb);
				sendCmd(device.getOpenCmd());
			}
			power = !power;
			DeviceManager.getInstance().setDeviceState(id, power);
			break;

		default:
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				needToCheck = false;
				mPowerB.setBackgroundResource(R.drawable.kaiguan12x);
				bg.setBackgroundResource(R.drawable.bb);
				power = true;
				break;
			case 1:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				needToCheck = false;
				mPowerB.setBackgroundResource(R.drawable.kaiguan22x);
				bg.setBackgroundResource(R.drawable.btn065);
				power = false;
				break;
			case 2:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				needToCheck = false;
				break;
			case 4:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				ToastShow.Show(getApplicationContext(), "获取状态失败：连接超时或设备未通电");
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_switch;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mSVProgressHUD = new SVProgressHUD(RemoteSwitchActivity.this);
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mTitleTv = $(R.id.title_tv);
		mPowerB = $(R.id.power_b);
		bg = $(R.id.bg);
		boolVersion();
		mBackL.setOnClickListener(this);
		mPowerB.setOnClickListener(this);
		address = getIntent().getStringExtra("address");
		Log.i("wmy", "address = " + address);
		id = getIntent().getStringExtra("id");
		power = DeviceManager.getInstance().checkDeviceState(id);
		if (power) {
			mPowerB.setBackgroundResource(R.drawable.kaiguan12x);
			bg.setBackgroundResource(R.drawable.bb);
		} else {
			mPowerB.setBackgroundResource(R.drawable.kaiguan22x);
			bg.setBackgroundResource(R.drawable.btn065);
		}
		device = DeviceManager.getInstance().getDeviceById(id);
		mTitleTv.setText("开关：" + device.getDeviceName());
		socket = SocketManager.getInstance().sMap.get(DeviceManager.getInstance().getmWlanId());
		if (socket == null) {
			ToastShow.Show(getApplicationContext(), "没有找到所绑定网关，无法控制该设备!");
			finish();
		}
		checkStatus();
	}

	public void checkStatus() {
		mSVProgressHUD.showWithStatus("正在获取设备状态");
		// device.checkStatus();
		check();
		socket.setRecDataCallBackListener_Serach(new RecDataCallBackListener_Serach() {

			@Override
			public void onReceiveData(String data) {
				// TODO Auto-generated method stub
				received = true;
				parseRecData(data);
			}
		});
		SocketManager.getInstance().setOnDeviceStatusListener(new OnDeviceStatusListener() {

			@Override
			public void onStatus(String data, int what) {
				// TODO Auto-generated method stub
				received = true;
				mHandler.sendEmptyMessage(what);
			}
		});
//		mHandler.sendEmptyMessageDelayed(2, 8 * 1000);
		checkTimeout();
	}
	
	private void checkTimeout(){
		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if(!received){
					mHandler.sendEmptyMessage(4);
				}
			}
		}, 10*1000);
	}

	private void check() {

		if (times < 3 && needToCheck) {
			times++;
			device.checkStatus();
		} else {
			return;
		}
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (needToCheck) {
					check();
				}
			}
		}, 3000);
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	private void parseRecData(String data) {
		if (data.length() < 10 || data == null) {
			return;
		}
		JSONObject jo;
		try {
			jo = new JSONObject(data);
			String a = jo.getString("a");
			if (a.equals("20000")) {
				int msgId = jo.getInt("b");
				String g = jo.getString("g");
				JSONObject jo1 = new JSONObject(g);
				JSONArray jsonArray = jo1.optJSONArray("data");
				int dataja[] = new int[jsonArray.length()];
				if (jsonArray != null) {
					for (int i = 0; i < jsonArray.length(); i++) {
						dataja[i] = (Integer) jsonArray.get(i);
					}
					if (dataja.length == 8) {
						if (dataja[(jsonArray.length() - 1)] == 121) {
							// Log.i("wmy", "获取ID为" + msgId + "的设备的状态为开");
							DeviceManager.getInstance().setDeviceState(msgId + "", true);
							mHandler.sendEmptyMessage(0);
						} else if (dataja[(jsonArray.length() - 1)] == 120) {
							// Log.i("wmy", "获取ID为" + msgId + "的设备的状态为关");
							DeviceManager.getInstance().setDeviceState(msgId + "", false);
							mHandler.sendEmptyMessage(1);
						} else if (dataja[(jsonArray.length() - 1)] == 255) {
							// Log.i("wmy", "获取ID为" + msgId + "的设备的状态为开");
							DeviceManager.getInstance().setDeviceState(msgId + "", true);
							mHandler.sendEmptyMessage(0);
						} else if (dataja[(jsonArray.length() - 1)] == 0) {
							// Log.i("wmy", "获取ID为" + msgId + "的设备的状态为关");
							DeviceManager.getInstance().setDeviceState(msgId + "", false);
							mHandler.sendEmptyMessage(1);
						}
					} else if (dataja.length == 11) {
						if (dataja[7] == 255) {
							// Log.i("wmy", "获取ID为" + msgId + "的设备的状态为开");
							DeviceManager.getInstance().setDeviceState(msgId + "", true);
							mHandler.sendEmptyMessage(0);
						} else if (dataja[7] == 0) {
							// Log.i("wmy", "获取ID为" + msgId + "的设备的状态为关");
							DeviceManager.getInstance().setDeviceState(msgId + "", false);
							mHandler.sendEmptyMessage(1);
						}
					}
				}
			}

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	private void sendCmd(String cmd) {
		if (socket.isLocalSuccess()) {
			socket.sendMqttData(cmd);
		} else {
			SocketManager.getInstance().sendRemoteData(socket.getMac(), device.getMainDeviceId(), cmd);
		}
	}
}
